import sys
from linkkit import linkkit
import threading
import traceback
import inspect
import time
import logging
import json
from openai import OpenAI


def get_response(messages):
    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        # model="qwen-turbo-latest",
        model="deepseek-r1-0528",
        messages=messages
    )
    return completion


messages = [{'role': 'system', 'content': '你是一个智慧农业决策者，会给你提供当前室内温度(temperature)、湿度(Humidity)、风速(WindSpeed)、光照强度(LightLux)、土壤湿度(soilHumidity)、紫外线(UV)、空气质量(AQI)等数据，你要决策风扇转速(FanLevel， 取值范围0-5)、光照强度(LEDLux，取值范围0-5)、水泵开关(IrrigationPumpStatus，取值范围0-1)是否调整。'}, {
    'role': 'system', 'content': '数据输出格式：{"FanLevel": 0, "LEDLux": 5, "IrrigationPumpStatus": 0}'}, {
    'role': 'system', 'content': '如果输入的格式不对，或者提问无关的内容，你不能回复其他的内容，直接回复：{"fanSpeed": 0, "led": 0}'}]


"""
 "temperature": 23.5,
        "Humidity": 24.1,
        "WindSpeed": 5.2,
        "UV": 20.5,
        "AQI": 200,
        "LightLux": 20.5,
        "soilHumidity": 20.5

         "IrrigationPumpStatus": 0,
        "FanLevel": 1,
        "LEDLux": 200

"""

# config log
__log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s'
logging.basicConfig(format=__log_format)

lk = linkkit.LinkKit(
    host_name="cn-shanghai",
    product_key="k01baZKR6Hv",
    device_name="Mqtt_Py",
    device_secret="fffe7d49d6f230d0e1ad1d4d5352f034")
lk.enable_logger(logging.WARN)


def on_device_dynamic_register(rc, value, userdata):
    if rc == 0:
        print("dynamic register device success, value:" + value)
    else:
        print("dynamic register device fail, message:" + value)


def on_connect(session_flag, rc, userdata):
    print("on_connect:%d,rc:%d" % (session_flag, rc))
    pass


def on_disconnect(rc, userdata):
    print("on_disconnect:rc:%d,userdata:" % rc)


def on_topic_message(topic, payload, qos, userdata):
    print("接收到消息：")
    payload = payload.decode('utf-8')
    jsonf = json.loads(payload)

    messages.append({'role': 'user', 'content': jsonf["params"]})
    assistant_output = get_response(messages).choices[0].message.content
    # 将大模型的回复信息添加到messages列表中
    messages.append({'role': 'assistant', 'content': assistant_output})

    print(f'模型输出：{assistant_output}')
    pass


def on_subscribe_topic(mid, granted_qos, userdata):
    print("on_subscribe_topic mid:%d, granted_qos:%s" %
          (mid, str(','.join('%s' % it for it in granted_qos))))
    pass


def on_unsubscribe_topic(mid, userdata):
    print("on_unsubscribe_topic mid:%d" % mid)
    pass


def on_publish_topic(mid, userdata):
    print("on_publish_topic mid:%d" % mid)


lk.on_device_dynamic_register = on_device_dynamic_register
lk.on_connect = on_connect
lk.on_disconnect = on_disconnect
lk.on_topic_message = on_topic_message
lk.on_subscribe_topic = on_subscribe_topic
lk.on_unsubscribe_topic = on_unsubscribe_topic
lk.on_publish_topic = on_publish_topic


lk.config_device_info("Eth|03ACDEFF0032|Eth|03ACDEFF0031")
lk.connect_async()
lk.start_worker_loop()
rc, mid = lk.subscribe_topic(
    "/k01baZKR6Hv/Mqtt_Py/user/update")
if rc == 0:
    print("subscribe topic success:%r, mid:%r" % (rc, mid))
else:
    print("subscribe topic fail:%d" % rc)


def publish_params(json_data):
    rc, mid = lk.publish_topic(
        "/k01baZKR6Hv/Mqtt_Py/user/get", json_data)
    if rc == 0:
        print("publish topic success:%r, mid:%r" % (rc, mid))
    else:
        print("publish topic fail:%d" % rc)


while True:
    time.sleep(1)
